import axios from "axios";
import store from "@/store";
import { ElLoading, ElMessage } from "element-plus";

const baseURL = import.meta.env.VITE_BASE_URL;

let loading = null;
const openFullScreen2 = () => {
  loading = ElLoading.service({
    lock: true,
    text: "Loading",
    background: "rgba(255, 255, 255, 0.4)"
  });
};
const service = axios.create({
  baseURL: baseURL,
  timeout: 8000,
  withCredentials: false,
  headers: {
    "Content-Type": "application/json;charset=UTF-8",
    Accept: "application/json"
  },
  responseType: "blob"
});

// 请求前的统一处理
service.interceptors.request.use(
  config => {
    if (config.method == "put" || config.method == "post") {
      openFullScreen2();
    }
    // JWT鉴权处理
    // if (store.getters['user/token']) {
    //   config.headers['token'] = store.state.user.token
    // }

    const token = store.state.user.token;
    // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
    config.headers["Authorization"] = token;
    return config;
  },
  error => {
    if (loading) {
      loading.close();
    }
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  response => {
    if (loading) {
      setTimeout(() => {
        loading.close();
      }, 300);
    }
    // const res = response
    // return response
    console.log(response, "response-");
    if (response.data.type === "application/json") {
      //报错提示
      const reader = new FileReader();
      reader.readAsText(response.data);
      reader.onload = () => {
        showError(JSON.parse(reader.result));
        return Promise.reject(response);
      };
    } else {
      return response;
    }
  },

  error => {
    if (loading) {
      loading.close();
    }
    console.log(error); // for debug
    const badMessage = error.message || error;
    const code = parseInt(
      badMessage
        .toString()
        .replace("Error: Request failed with status code ", "")
    );
    // showError({ code, message: badMessage })
    showError(error);
    return Promise.reject(error);
  }
);

function showError(error) {
  // console.log(error)
  // debugger
  if (error.code === 2) {
    // to re-login
    store.dispatch("user/loginOut");
  } else {
    // alert(error.msg || error.message || '服务异常')
    ElMessage({
      message: error.msg || error.message || "服务异常",
      type: "error",
      duration: 3 * 1000
    });
  }
}

export default service;
